package com.tanhua.server.interceptor;

import com.alibaba.fastjson.JSON;
import com.tanhua.domain.db.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.time.Duration;

/**
 * @author liuyp
 * @date 2021/01/26
 */
@Component
public class TokenInterceptor implements HandlerInterceptor {

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1. 接收token值
        String token = request.getHeader("Authorization");
        if (token == null) {
            response.setStatus(401);
            return false;
        }

        //2. 从redis里找到token对应的用户
        User user = findByToken(token);
        if (user == null) {
            response.setStatus(401);
            return false;
        }

        //3. 把User绑定到当前线程上
        UserHolder.setUser(user);
        return true;
    }

    private User findByToken(String token) {
        String json = redisTemplate.opsForValue().get("TOKEN_" + token);
        if (json != null) {
            //是登录状态，Redis里有数据，就要给redis数据再次设置有效期：1小时
            redisTemplate.opsForValue().set("TOKEN_" + token, json, Duration.ofHours(1));
            //把json数据还原成User对象
            return JSON.parseObject(json, User.class);
        }

        return null;
    }
}
